package com.bentley.kotlindemo.ui.kits.authorlist_paging

import androidx.paging.LoadState
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.bentley.kotlindemo.db.entity.ArticleItemBean
import com.bentley.kotlindemo.net.ApiService

/**
 * <pre>
 *  ┌────────────────────────────────────────────
 *  │ @author  Lee  @date 2021/3/25 13:48
 *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
 *  │ @desc 作者分页数据源
 *  └────────────────────────────────────────────
 *  中文分页教程
 *  https://blog.csdn.net/qq_36699930/article/details/109805639?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-1&spm=1001.2101.3001.4242
 * </pre>
 */
class AuthorPagingPostDataSource(private val apiService: ApiService) : PagingSource<Int, ArticleItemBean>() {

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticleItemBean> {
        try {

            //param.key为空时，默认加载第1页数据。
            val currentPage = params.key ?: 1
            //获取网络数据
            val response = apiService
                .getListData(currentPage)
            //请求成功使用LoadResult.Page返回分页数据，prevKey 和 nextKey 分别代表前一页和后一页的索引。
            return LoadResult.Page(
                //加载的数据
//                data = response.data.datas,
                data = response.data,

                //上一页，如果有上一页设置该参数，否则不设置
                prevKey =  if (currentPage>1) currentPage - 1 else 0,

                //加载下一页的key 如果传null就说明到底了
                nextKey = if (response.page >= response.total_pages) null else currentPage + 1
//                nextKey =  currentPage + 1
            )

        } catch (e: Exception) {
            return LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, ArticleItemBean>): Int? {
        TODO("Not yet implemented")
    }


}